package top.jiangqiang.crawler.core.http.entities;

import org.dromara.hutool.core.text.StrUtil;
import top.jiangqiang.crawler.core.http.constants.HeaderName;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;


public class RequestHeader implements Serializable {

    private final Map<HeaderName, String> header = new HashMap<>();

    public void addHeader(HeaderName headerName, String value) {
        this.header.put(headerName, value);
    }
    public void addHeader(String headerName, String value) {
        this.header.put(HeaderName.of(headerName), value);
    }

    public String getHeader(String headerName) {
        return this.header.get(HeaderName.of(headerName));
    }

    public String getHeader(HeaderName headerName) {
        return this.header.get(headerName);
    }

    public void mergeHeader(HeaderName headerName, String value) {
        if (StrUtil.isBlank(getHeader(headerName))) {
            this.header.put(headerName, value);
        }
    }

    public void mergeHeader(RequestHeader requestHeader) {
        if (requestHeader != null && !requestHeader.isEmpty()) {
            requestHeader.forEach(this::mergeHeader);
        }
    }

    public void mergeHeader(String headerName, String value) {
        if (StrUtil.isBlank(getHeader(headerName))) {
            this.header.put(HeaderName.of(headerName), value);
        }
    }

    public boolean isEmpty() {
        return header.isEmpty();
    }

    public void forEach(BiConsumer<? super HeaderName, ? super String> action) {
        header.forEach(action);
    }
}
